package fx.listener;

import fx.TransparentForm;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class WheelListener implements EventHandler<ScrollEvent> {

    private final Stage stage;

    private Node root;

    private static final int MAX_FONT = 30;
    private static final int MIN_FONT = 11;
    private static final int MAX_WIDTH = 180;
    private static final int MIM_WIDTH = 80;
    private static final int MAX_HEIGHT = TransparentForm.stock.size() * 30;
    private static final int MIM_HEIGHT = TransparentForm.stock.size() * 15;

    public WheelListener(Stage stage, Node root) {
        this.stage = stage;
        this.root = root;
    }

    public void enableDrag(Node node) {
        node.setOnScroll(this);
    }

    @Override
    public void handle(ScrollEvent event) {
        double deltaY = event.getDeltaY();
        double width = stage.getWidth();
        double height = stage.getHeight();
        double ratio = height / width;
        double value = 5;
        if (deltaY < 0) {
            stage.setWidth((width - (value)) < MIM_WIDTH ? MIM_WIDTH : (width - (value)));
            stage.setHeight((height - (value * ratio)) < MIM_HEIGHT ? MIM_HEIGHT : (height - (value * ratio)));
            for (int i = 0; i < TransparentForm.stock.size(); i++) {
                Text text = (Text) ((VBox) root).getChildren().get(i);
                text.setFont(new Font((text.getFont().getSize() - 1) < MIN_FONT ? MIN_FONT : text.getFont().getSize() - 1));
            }
        } else {
            stage.setWidth((width + (value)) > MAX_WIDTH ? MAX_WIDTH : (width + (value)));
            stage.setHeight((height + (value * ratio)) > MAX_HEIGHT ? MAX_HEIGHT : height + (value * ratio));
            for (int i = 0; i < TransparentForm.stock.size(); i++) {
                Text text = (Text) ((VBox) root).getChildren().get(i);
                text.setFont(new Font((text.getFont().getSize() + 1) > MAX_FONT ? MAX_FONT : text.getFont().getSize() + 1));
            }
        }
        event.consume();
    }
}
